package com.data_structure_algorithm.data_structure.queue;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc 环形队列
 */
public class CireleArrayQueue {

  //前言 +1 是为了区分队空和队满(会浪费一个空间)
  //队空条件 head == tail
  //队满条件 (tail + 1 ) % max = head
  //入队变化(tail变化) ----> tail = (tail + 1 ) % max
  //出队变化(head变化) ----> head = (head + 1 ) % max


  int max;

  int[] queue;

  int head;

  int tail;

  public CireleArrayQueue(int max) {
    this.max = max;
    queue = new int[max];
  }

  public void add(int a) {
    if (isFull()) {
      System.out.println("容量已满");
      return;
    }






    //注意：直接存储，因为tail是值为0，符合索引标准
    queue[tail] = a;
    //tail指针移动,考虑下标越界
    tail = (tail + 1) % max;

  }


  public int get() {
    if (isEmpty()) {
      throw new RuntimeException("队列为空");
    }

    //获取数据尾不变 头往后移动
    int tempValue = queue[head];
    //考虑下标越界
    head = (head + 1) % max;
    return tempValue;
  }

  //是否队满
  private boolean isFull() {
    //tail = (tail + 1) % max
    //head = (head + 1) % max
    //如果此时tail == head 说明满了
    return (tail + 1) % max == head; // +1是为了区分队空和队满
  }

  //是否队空
  private boolean isEmpty() {

    return tail == head;
  }

  public void print() {
    //确定当前有效的数据个数
    int effectiveElement = (tail + max - head) % max;
    //effectiveElement + head代表从头开始的有效个数
    // head 开始遍历
    for (int i = head; i < effectiveElement + head; i++) {
      System.out.println(queue[i % max]);//环形会下标越界
    }


    

  }


  public static void main(String[] args) {
    CireleArrayQueue cireleArrayQueue = new CireleArrayQueue(3);
    System.out.println("开始add");
    cireleArrayQueue.add(10);
    cireleArrayQueue.add(11);


    cireleArrayQueue.print();
    System.out.println("开始get");
    cireleArrayQueue.get();
    cireleArrayQueue.get();

    cireleArrayQueue.add(13);
    cireleArrayQueue.add(14);
    //System.out.println(cireleArrayQueue.get());
    cireleArrayQueue.print();


  }


}
